<script lang='ts' setup>
import { getPicture } from '@/assets/工具/工具类';
import TitleBar from '@/components/标题.vue'
import { onBeforeMount, ref } from 'vue';
import axios from '@/assets/工具/网络请求.ts';
import { useCascaderAreaData } from '@vant/area-data';
import type { UserInfo } from '@/types';
import {  showToast } from 'vant';

import backgroundImage from '../assets/图片/校园/长安.png';
import {  onMounted } from 'vue';
import { routes } from 'vue-router/auto-routes';
import router from '@/router';
const imageUrls = ref<string[]>([]);
  const color = ref(false)
  const userInfo1 = ref(false)
  const change = ref(true)
  const see = ref(true)


  
  const userImg = ref()
// 定义一个类型来表示图片模块的导出结构
type ImageModule = {
  default: string;
};

let sex = '' ;
onMounted(async () => {
  // 使用 import.meta.glob 批量导入指定目录下的所有图片文件
  const imageModules = import.meta.glob<ImageModule>('@/assets/图片/backgroundImage/*.{png,jpg,jpeg,gif}');
  const urls: string[] = [];

  // 遍历导入的图片模块
  for (const path in imageModules) {
    const module: ImageModule = await imageModules[path]();
    // 将图片的 URL 添加到数组中
    urls.push(module.default);
    
  }

  imageUrls.value = urls;
  
});


onBeforeMount(

async () =>{
  if(sessionStorage.getItem('token')){
  const id = sessionStorage.getItem('token')
  const date = await axios.doGet(`/UpUserInfoServlet?id=${id}`)
  User.value = date.data
  userImg.value = User.value.userUrl
  sex = User.value.userSex;
}else{
  see.value = false
}

  }
)
const imgRandom = ref(`${backgroundImage}`)


const imageUrl = () => {

  imgRandom.value = imageUrls.value[Math.floor(Math.random() * imageUrls.value.length)];
};



const User = ref({} as UserInfo)

const file = ref<File | null>(null);

const onFileChange = (e: Event) => {
  const target = e.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    file.value = target.files[0];
    uploadImage()
  } else {
    file.value = null; // 如果没有文件，设置为 null
  }
};

const uploadImage = async () => {
  if (!file.value) return;
  const formData = new FormData();
  formData.append('image', file.value);
  const id = sessionStorage.getItem('token')

  try {
    const response = await axios.doPost(`/upload?id=${id}`,formData);
    User.value.userUrl = response.data.userUrl; 
    console.log(User.value.userUrl+'值是');
    userImg.value = User.value.userUrl
  } catch (error) {
    console.error('上传图片失败:', error);
  }
};



User.value.name = ''





// 定义区域数据选项的类型
type AreaOption = {
  text: string;
  value: string | number;
  // 这里可以根据实际数据结构添加更多属性
};

const show = ref(false);
const fieldValue = ref('');
const cascaderValue = ref('');
const options = useCascaderAreaData();

const onFinish = ({ selectedOptions }: { selectedOptions: AreaOption[] }) => {
  show.value = false;
  fieldValue.value = selectedOptions.map((option: AreaOption) => option.text).join('/');
  User.value.address = fieldValue.value
  
};



const personalCenter =  async() =>{
  if(sessionStorage.getItem('token')){
    User.value.userId = parseInt(sessionStorage.getItem('token')!)
     await axios.doPost('UpUserInfoServlet',User.value)
  
    
    userInfo1.value = !userInfo1.value
    showToast(' 小匡提醒您，更改成功！');
  }
 
}
 const phont = ref(false)


const columns = [
  { text: '绿色', value: 'rgb(18, 216, 51,0.8)' },
  { text: '粉红色', value: 'rgb(255, 192, 203,0.8)' },
  { text: '粉红', value: 'rgb(255, 192, 203,0.4)' },
  { text: '棕色', value: 'rgb(165,167,169,0.6)' },
  { text: '青绿色', value: 'rgb(42,194,210,0.6)' },
];
const selectedValues = ref(['rgb(255, 192, 203,0.4)']);


const showPopover = ref(true);
const handleAvatarClick = (event: Event) => {
  change.value = !change.value
  showPopover.value = !showPopover.value
  event.stopPropagation();
  phont.value = !phont.value;
  
};

const handleAvatarClick1 = (event: Event) => {
  event.stopPropagation();
  color.value = !color.value;
  userIS.value = !userIS.value
 
};

const cancle = () => {
  userInfo1.value = !userInfo1.value
  User.value.userSex = sex
  showToast('小匡提醒您，已取消')
  
}

const logout =() =>{
  sessionStorage.removeItem('token');
window.location.href = '/PersonalCenter'
}
const userIS = ref(true)
interface Offset {
  x: number;
  y: number;
}
const onOffsetChange = (offset :Offset) => {
      // showToast(`x: ${offset.x.toFixed(0)}, y: ${offset.y.toFixed(0)}`);
    };


const userId = ref(sessionStorage.getItem('token'))

</script>

<template>
    <div class="组件根元素" >
        <TitleBar title="个人中心"/>
        <van-notice-bar left-icon="volume-o" :scrollable="false">
  <van-swipe
    vertical
    class="notice-swipe"
    :autoplay="3000"
    :touchable="false"
    :show-indicators="false"
  >
    <van-swipe-item @click="phont = !phont">点击头像可换！</van-swipe-item>
    <van-swipe-item>点击背景可以更换颜色！</van-swipe-item>
    <van-swipe-item>今人不见古时月，今月曾经照古人。</van-swipe-item>
  </van-swipe>
</van-notice-bar>
        <div @click="imageUrl" class="personal_center" :style="{ 'background-image' : `url(${imgRandom})` }">
<div @click="handleAvatarClick" v-if="User.userUrl"><img :src="getPicture(User.userUrl)" alt=""></div>
<div @click="handleAvatarClick" v-else-if="User.userSex =='男'"><img src="@/assets/图片/通用/男.png" alt=""></div>
<div @click="handleAvatarClick" v-else-if="User.userSex =='女'"><img src="@/assets/图片/通用/女.png" alt=""></div>
<div @click="handleAvatarClick" v-else><img src="@/assets/图片/通用/未知.jpg" alt=""></div>
<div @click="handleAvatarClick1" :style="{'background-color': `${selectedValues}` }" class="name" v-if="User.name">{{ User.name }}</div>
<div @click="handleAvatarClick1" :style="{'background-color': `${selectedValues}`}" class="loginCreate" v-else>
  <p><span @click="$router.push('/login')" >登录</span></p>
  <p >/</p>
  <p><span @click="$router.push('/CreateUser')" >注册</span></p></div>
        </div>

        <van-picker style="position: absolute; width: 100%;" @click="color = !color" v-if="color" v-model="selectedValues" title="背景颜色" :columns="columns" />
        <div v-if="userInfo1" class="userInfo">
          <div> 姓名：<input type="text" v-model="User.name">
          </div>
          <div> 性别：<input type="text" v-model="User.userSex">
          </div>
          <div> 地址：<input  v-model="User.address" @click="show = true"  type="button" name="" id="" >
          </div>
          <div> 邮件：<input type="text" v-model="User.email">
          </div>
          <div> 电话：<input type="text" v-model="User.userPhone">
          </div>
          <div id="kencal"><div @click="cancle">取消</div><div @click="personalCenter" >确定</div> </div>

        </div>
        <div v-if="!userInfo1 && change && see" class="update12" @click="userInfo1 = !userInfo1"  >
          <span>更改信息</span>
        </div>



        
    



<van-popup v-model:show="show" round position="bottom">
  <van-cascader
    v-model="cascaderValue"
    title="请选择所在地区"
    :options="options"
    @close="show = false"
    @finish="onFinish"
  />
</van-popup>




        <input v-if="phont && see" class="Update" type="file" @change="onFileChange"  />
        <!-- <button @click="uploadImage">上传图片</button> -->
        <!-- <div v-if="userIS" @click="logout" class="log_out">退出登录</div> -->


       

        <div  v-if="(!userInfo1 && change && see && userIS) "  @click="logout" class="log_out">退出登录</div>

        <!-- <div v-if="userId" class="userIdS">
          <van-popover v-model:show="showPopover">
  <van-grid
    square
    clickable
    :border="false"
    column-num="3"
    style="width: 240px;"
  >
    <van-grid-item
      v-for="i in 6"
      :key="i"
      text="选项"
      icon="photo-o"
      @click="showPopover = false"
    />
  </van-grid>
  <template #reference>
    <van-button type="primary">自定义内容</van-button>
  </template>
</van-popover>
        </div> -->
        <div v-else-if="!userInfo1 && showPopover && !userId">
          <van-empty description="您还没有登录，登陆试试吧">
   
   <van-button @click="$router.push('/login')" round type="primary" class="bottom-button">登  录</van-button>
 </van-empty>
        </div>
     
        
    </div>
</template>
<style scoped>
.van-grid-item{
  margin: auto;
}
.van-button{
  text-align: center;
}
.userIdS{
  margin: auto;
  padding-left: 100px;
}
  .bottom-button {
    width: 160px;
    height: 40px;
    letter-spacing: 16px;
  }
#kencal div{
  background-color: rgb(149, 153, 153);
  border-radius: 10px;
  width: 100px;
}
#kencal {
  display: flex;
  line-height: 100px;
  justify-content: space-around;
  width: 240px;
  
}
.update12{
  position: absolute;
 top: 300px;

  width: 80px;
  left: 40px;
  border-radius: 10px;
  font-size: 16px;
  text-align: center;
  line-height: 36px;
  background-color: rgb(12, 163, 163);
  border: 1px solid rgb(255, 92, 92);
  
}
.userInfo {
  position: absolute;
  margin-top: 100px;
  background-color: antiquewhite;
  width: 343px;
  margin: auto;
  left: 16px;
  top: 350px;
  border-radius: 10px;
  font-size: 16px;
  height: 280px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
 
}
.userInfo input{

  width: 160px;
  margin: auto;
}
.userInfo div{
  width: 343px;
 margin: auto;
 text-align: center;
  line-height: 30px;
}
.name{
  text-align: center;
  border-radius: 40px 0px 40px 0px;
  color: rgb(18, 216, 51);
}
  .notice-swipe {
    height: 40px;
    line-height: 40px;
  }
.Update{
  position: absolute;
  color: aliceblue;
  width: 120px;
  
  font-size: 12px;
  background-color: rgb(255, 192, 203,0.8);
  border-radius:  20px 0 20px 0px;
  z-index: 4;
  top: 315px;
  left: 30px;
  
}
.loginCreate{
  display: flex;
  font-size: 20px;
  padding-left: 60px;
  box-sizing: border-box;
  border-radius: 0px 40px 0 40px;
  
}
.loginCreate p{
  width: 40px;
  text-align: center;
  padding: 0;
  margin: 0;
  color: rgb(255, 0, 0);
  display: inline;
}
.loginCreate p:nth-child(2){
  width: 20px;

}
input{
  width: 80px;
}


.log_out{
    position: fixed;
    width: 300px;
    line-height: 50px;
    text-align: center;
    background-color: rgb(250, 235, 215);
    margin:20px auto;
    border-radius: 25px;
    top: 600px;
    left: calc(50% - 150px);
    z-index: 3;
}
.personal_center{
    width: 343px;
    background-color:rgb(255, 192, 203,0.9);
    
    height: 300px;
    margin: 0;
    background-size: 100% 100%;
    line-height:300px;
    margin: auto;
    display: flex;
    justify-content: space-evenly;
    position: relative;
}
.personal_center div{
    width: 10px;
    margin-top: 100px;
    height: 100px;
    line-height: 100px;
    /* background-color: rgb(250, 235, 215,0.6); */
}
.personal_center div:nth-child(1) ,img{
    border-radius: 50%;
    width: 100px;
}
.personal_center div:nth-child(2){
    width: 200px;
}
.personal_center div, img{
  width: 100px;
  height: 100px;
}
.组件根元素{
  width: 376px;

}
</style>
